<?php
/**
 * Author:xsc
 * Time:2023/11/28 13:57
 */

namespace App\Service\Common;

use App\Service\BaseService;
use App\Repository\OpenPlatformRepo;

class ResponseService extends BaseService
{

    private $self_public_key_path;

    private $self_private_key_path;

    public function __construct()
    {
        if (env('APP_ENV') == 'pro') {
            $app_env = 'pro';
        } else {
            $app_env = 'test';
        }
        $this->self_public_key_path = base_path() . '/keys/self/' . $app_env . '_public.pem';
        $this->self_private_key_path = base_path() . '/keys/self/' . $app_env . '_private.pem';
    }

    /**
     * 统一构建响应体
     * @param int $error_code
     * @param string $error_msg
     * @param array $data
     * @param string $platform_no
     * @return array
     * @throws \App\Exceptions\BusinessException
     * Author:xsc
     * Time:2023/11/28 15:03
     */
    public function return(int $error_code, string $error_msg, array $data, string $platform_no): array
    {
        $response = [
            'error_code' => $error_code,
            "error_msg"  => $error_msg,
            //'data'       => '',
            //'sign'       => '',
            //'encryptKey' => '',
            'timestamp'  => time(),
        ];

        // 接入平台信息
        $platform_info = OpenPlatformRepo::getInstance()->getInfoByPlatformNo($platform_no);

        // 接入平台公钥
        $public_key = $platform_info['public_key'];

        // 开放平台私钥
        $self_private_key = file_get_contents($this->self_private_key_path);

        $sign_data = CheckSignService::getInstance()->selfRequestCreateSign($data, $public_key, $self_private_key);

        $response['data'] = $sign_data['data'];

        $response['sign'] = $sign_data['sign'];

        $response['encryptKey'] = $sign_data['encryptKey'];

        return $response;
    }

}
